import { Selector } from 'gantd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { getListApi } from './service';
import { getGantPopupContainer } from '@/utils/utils';
export interface BaseSelectItem {
  parentId: number;
  id: number;
  partId: number;
  nodeCode: string;
}

export type BaseSelectList = BaseSelectItem[];

interface SelectProps {
  cache: any;
  cacheKey: string;
  api: string;
  params?: any;
  labelProp?: string;
  valueProp?: string;
  onAfterQuery?: (dataSource: any[]) => any[];
}

const BaseSelect: React.FC<SelectProps> = (props) => {
  const { cache, cacheKey: customCacheKey, api, params, valueProp, onAfterQuery, ...restProps } = props;
  const [dataSource, setDataSource] = useState([]);

  //选择器 cacheKey需受valueProp值做区分
  const cacheKey = useMemo(() => {
    return valueProp == 'id' ? customCacheKey : valueProp + customCacheKey;
  }, [valueProp, customCacheKey]);

  const fetchData = useCallback(async () => {
    let task = null;
    task = cache.get(cacheKey);
    if (!task) {
      const res: BaseSelectList = await getListApi(api, params);
      task = (res.content || res).map((item) => {
        if (typeof item === 'string') {
          const id = item;
          cache.set(id, item);
          return { ...item, [valueProp!]: id };
        }
        const id = String(item[valueProp!]);
        cache.set(id, item);
        return { ...item, [valueProp!]: id };
      });
      cache.set(cacheKey, task);
    }
    setDataSource(onAfterQuery ? onAfterQuery(task) : task);
  }, [cacheKey, valueProp, onAfterQuery]);

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <Selector
      getPopupContainer={getGantPopupContainer}
      valueProp={valueProp}
      selectorId={cacheKey}
      dataSource={dataSource}
      {...restProps}
    />
  );
};

BaseSelect.defaultProps = {
  labelProp: 'nodeName',
  valueProp: 'id',
};

export default BaseSelect;
